package cc.wanforme.st.server.base.controller;


import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cc.wanforme.st.server.base.entity.User;
import cc.wanforme.st.server.base.service.IUserService;
import cc.wanforme.st.server.vo.ResMessage;
import cc.wanforme.st.server.vo.SearchQueryVo;
import cc.wanforme.st.server.vo.base.UserVo;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author wanne
 * @since 2023-01-03
 */
@Controller
@RequestMapping("/base/user")
public class UserController {

	@Autowired
	private IUserService userService;
	
	@PostMapping("/add")
	@PreAuthorize("hasAuthority('user:add')")
	@ResponseBody
	public ResMessage<User> add(@RequestBody User user) {
		userService.saveVo(user);
		user.setPassword(null);
		return ResMessage.success(user);
	} 
	
	@PostMapping("/update")
	@PreAuthorize("hasAuthority('user:update')")
	@ResponseBody
	public ResMessage<Void> update(@RequestBody User user) {
		userService.updateVo(user);
		return ResMessage.success();
	}
	
	@PostMapping("/resetpwd")
	@PreAuthorize("hasAuthority('user:update')")
	@ResponseBody
	public ResMessage<Void> resetPwd(@RequestBody User user) {
		userService.resetPwd(user.getId(), user.getPassword());
		return ResMessage.success();
	}
	
	@PostMapping("/del/{id}")
	@PreAuthorize("hasAuthority('user:delete')")
	@ResponseBody
	public ResMessage<Void> del(@PathVariable String id ) {
		userService.deleteUser(id);
		return ResMessage.success();
	}
	
	
	/** 查询，可以根据 name 和 username 模糊查询
	 * @param queryVo
	 * @return
	 */
	@PostMapping("/list")
	@PreAuthorize("hasAuthority('user:list')")
	@ResponseBody
	public ResMessage<PageInfo<UserVo>> list(@RequestBody SearchQueryVo<UserVo> queryVo) {
		PageInfo<User> result = null;
		UserVo param = queryVo.getParam();
		
		if(param!=null) {
			result = userService.searchUsers(queryVo.getPage(), queryVo.getSize(),
					param.getName(), param.getUsername(), param.getStatus());
		} else {
			result = userService.searchUsers(queryVo.getPage(), queryVo.getSize(),
					null, null, null);
		}
		
		PageInfo<UserVo> resultPageInfo = new PageInfo<UserVo>();
		BeanUtils.copyProperties(result, resultPageInfo, "list");
		if(result.getList() != null) {
			List<UserVo> collect = result.getList().stream().map(UserVo::new).collect(Collectors.toList());
			resultPageInfo.setList(collect);
		}
		
		return ResMessage.success(resultPageInfo);
	}
	
	
}
